// pages/main/index.js
let mta = require('../../utils/mta_analysis.js');
let util = require("../../utils/util");
let fetch = require("../../utils/fetch");
Page({
	data: {
		shopName: "",
		shopCount: 0,
		msg: "点我扫",
		note: "扫码购物",
		isShow: true,
		isError: false,
		urlAddress: getApp().globalData.imageUrl,
		right_distance: "-62rpx",
		topUrl: ' ',
		botUrl: ' ',
		bgUrl: '',
		bgType: ''
		// animationData: {}
	},
	onLoad: function(options) {
		mta.Page.init();
		mta.Event.stat("smg_index", {})
		if (getApp().globalData.common.souce == "0") {
			this.openTheDoor();
		}
		this.getFaceInfo();
		this.getSkin();
		console.log('getApp().globalData.common.shopCode')
		console.log(getApp().globalData.common.shopCode)

		if (!getApp().globalData.common.shopCode) {
			this.getBgImg();

		}
		// if (getApp().globalData.common.shopCode) {
		// 	this.getShopName();
		// }

	},
	onReady: function() {},
	onShow: function() {
		this.getFaceLocation();
		// 页面显示
		var _self = this;
		if (getApp().globalData.common.shopCode) {
			_self.getShopMarket();

		} else {
			_self.setData({
				shopName: "请扫店铺二维码",
				isShow: false
			});
		}
		this.popCoupons();


	},
	onHide: function() {
		// 页面隐藏
	},
	onUnload: function() {
		// 页面关闭
	},
	getSkin: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/skin/style.do',
			data: {
				shopCode: getApp().globalData.common.shopCode || '',
			},
			header: getApp().globalData.header,
			success: function(res) {
				console.log(res)
				if (res.data.code == 200) {
					_self.setData({
						topUrl: res.data.obj.topUrl,
						botUrl: res.data.obj.botUrl

					})
				} else {

				}
			}
		})
	},
	getBgImg: function() {
		var _self = this;

		wx.request({
			url: getApp().globalData.baseUrl + '/skin/getBackground.do',
			data: {
				longitude: getApp().globalData.common.longitude || '',
				latitude: getApp().globalData.common.latitude || ''
			},
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 200) {

					if (res.data.obj.backGroundType == 1) {
						_self.setData({
							bgUrl: res.data.obj.imgUrl,
							bgType: 'bgType_act'
						})
					} else {
						_self.setData({
							bgUrl: _self.fitImage(res.data.obj.weatherType),
							bgType: 'bgType_weat'
						})
					}
				}

			}
		})
	},
	getShopName: function() {
		if (!getApp().globalData.common.shopCode) {
			this.setData({
				shopName: "请扫店铺二维码"
			})
			return
		}
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/shop/getShop.do',
			data: {
				shopCode: getApp().globalData.common.shopCode || '',
			},
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 200) {
					getApp().globalData.common.longitude = res.data.obj.longitude;
					getApp().globalData.common.latitude = res.data.obj.latitudes;
					getApp().globalData.common.shopType = res.data.obj.shopType;
					//console.log(getApp().globalData.common.shopType);
					_self.getBgImg();
					_self.setData({
						shopName: res.data.obj.shopName
					});
				} else if (res.data.code == 507) {
					_self.setData({
						shopName: '门店歇业'
					});
				} else {
					_self.setData({
						shopName: '没有该门店'
					});
				}
			}
		})
	},
	getFaceInfo: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/wxappletMember/applet/getFaceStat.do',
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 405) {
					wx.showToast({
						title: '请重新上传人脸识别照片',
						image: '../../image/error.png',
						duration: 1000
					})
				} else {
					// _self.showMyToast(_self, "人脸合法")
				}
			}
		})
	},
	addShopMarket: function(code, num) {
		var _self = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/cart/addGoods.do',
			data: {
				gbk: code,
				shopCode: getApp().globalData.common.shopCode || '',
				num: num
			},
			header: getApp().globalData.header,
			success: function(res) {
				wx.hideLoading()
				if (res.data.code == 200) {
					_self.setData({
						obj: res.data.obj,
						isShow: true
					});
					if (res.data.obj.lastGoodsisNull) {
						_self.showMyToast(_self, "没有该商品")

					} else {
						_self.turn();
					}
				} else if (res.data.code == 507) {

					_self.showMyToast(_self, res.data.des)
				}

			}
		})
	},
	getShopMarket: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/cart/getCartGoodsNum.do',
			data: {
				shopCode: getApp().globalData.common.shopCode || '',
			},
			header: getApp().globalData.header,
			success: function(res) {
				_self.setData({
					shopCount: res.data.obj,
					isShow: true,
					note: "扫码购物"
				});
				if (res.data.obj) {
					_self.setData({
						right_distance: "44rpx"
					});
				} else {
					_self.setData({
						right_distance: "-62rpx"
					});
				}
			}
		})
	},
	turn: function(argument) {
		mta.Event.stat("smg_btshouyegouwuche", {});
		if (this.data.isShow) {
			wx.showLoading({
				title: '加载中',
				mask: true
			});
			getApp().globalData.common.isScanPage = true;

			const version = wx.getSystemInfoSync().SDKVersion;
			console.log("^^^^^^^^" + version)
			console.log("^^^^^^^^" + this.compareVersion(version, '2.1.0'));
			if (this.compareVersion(version, '2.1.0') != -1) {
				wx.navigateTo({
					url: '../newScan/newScan'
				})
			} else {
				wx.navigateTo({
					url: '../scan/scan'
				})
			}
			wx.hideLoading()
		} else {
			this.scanShops();
		}
	},

	compareVersion: function(v1, v2) {
		v1 = v1.split('.')
		v2 = v2.split('.')
		const len = Math.max(v1.length, v2.length)

		while (v1.length < len) {
			v1.push('0')
		}
		while (v2.length < len) {
			v2.push('0')
		}

		for (let i = 0; i < len; i++) {
			const num1 = parseInt(v1[i])
			const num2 = parseInt(v2[i])

			if (num1 > num2) {
				return 1
			} else if (num1 < num2) {
				return -1
			}
		}

		return 0
	},


	chickAction: function() {
		if (this.data.isShow) {
			mta.Event.stat("smg_scan", {})
			this.scanGoods();
		} else {
			mta.Event.stat("smg_positon", {})
			this.scanShops();
		}
	},
	scanShops: function() {
		var _self = this;
		wx.showModal({
			title: '提示',
			content: '请先扫描店铺二维码',
			showCancel: true,
			success: function(res) {
				if (res.confirm) {
					wx.scanCode({
						success: (res) => {
							console.log(res);
							if (res.result.split("?")[1]) {
								var url = '?' + res.result.split("?")[1];
								var args = _self.fitUrl(url);
								var shopCode = args.shopCode;
								var type = args.souce;
								var shopType = args.ST;
								if (!shopCode) {
									wx.showToast({
										title: '此码非小程序码',
										image: '../../image/error.png',
										duration: 1000
									})
								} else {
									shopType = shopCode.split("&")[2];
									if (shopType) {
										shopType = shopType.split("=")[1];
									};
									getApp().globalData.common.shopCode = shopCode;
									getApp().globalData.common.souce = type;
									_self.getShopMarket();
									_self.getShopName();
									wx.setStorageSync('shopCode', shopCode);
									if (type == '0') {
										_self.openTheDoor();
									}


								}

							} else {
								console.log('小程序二维码')

								if (!res.path) {
									wx.showToast({
										title: '此码非小程序码',
										image: '../../image/error.png',
										duration: 1000
									})
									return;
								}
								var url = '?' + res.path.split("?")[1];
								var args = _self.fitUrl(url);
								var shopCode = args.shopCode;
								var type = args.souce;
								var shopType = args.ST;
								getApp().globalData.common.shopCode = shopCode;
								getApp().globalData.common.souce = type;
								_self.getShopMarket();
								_self.getShopName();
								wx.setStorageSync('shopCode', shopCode);
								if (type == '0') {
									_self.openTheDoor();
								}

							}
						}
					})
				}
			}
		})
	},
	scanGoods: function() {
		var _self = this;

		wx.scanCode({
			success: (res) => {
				console.log(res)
				var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
				console.log(pattern.test(res.result))
				if (!pattern.test(res.result)) {
					// _self.addShopMarket(res.result, 1);
					_self.filterNum(res.result);
				} else {
					wx.hideLoading();
					_self.showMyToast(_self, "非商品条码")
				}
			},
			fail: (res) => {
				_self.turn();
				// console.log('fail')
			}
		})
	},
	openTheDoor: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/shop/scanRqOpenDoor.do',
			data: {
				shopCode: getApp().globalData.common.shopCode,
			},
			header: getApp().globalData.header,
			success: function(res) {
				//console.log(res)
				getApp().globalData.common.souce = "1"
				if (res.data.code == 200) {
					wx.showToast({
						title: '开门成功',
						icon: 'success',
						duration: 2000
					})
				} else if (res.data.code == 507) {
					// wx.showToast({
					//     title: '开门成功',
					//     icon: 'success',
					//     duration: 2000
					// })
					_self.showMyToast(_self, res.data.des, 2000)
				}
			},
			fail: function() {}
		})
	},
	showMyToast: function(self, my_toast_tip, time = 1000, template = 'my_toast') {
		self.setData({
			template: template, //my_toast
			my_toast_tip: my_toast_tip
		})
		var timer = setTimeout(() => {
			self.setData({
				template: '', //my_toast
				my_toast_tip: ''
			})
			clearTimeout(timer);
		}, time)

	},
	addPayGoods: function(code) {
		var _self = this;

		wx.request({
			url: getApp().globalData.baseUrl + '/applet/pay/getPayAmount.do',
			data: {
				gbk: code,
				shopCode: getApp().globalData.common.shopCode,
			},
			header: getApp().globalData.header,
			success: function(res) {
				wx.hideLoading()
				if (res.data.code == 200) {
					_self.payGoodsAction(res.data.obj.amount, code)
				} else {
					_self.showMyToast(_self, res.data.des)

				}

				//_self.payGoods(code);

			}
		})

	},
	getFaceLocation: function() {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/shop/getFaceLocation.do',
			method: 'get',
			header: getApp().globalData.header,
			data: {
				openId: wx.getStorageSync('openId'),
			},
			success: function(res) {

				console.log("人脸识别结果")
				console.log(res)
				//console.log(res)

				wx.hideLoading();
				if (res.data.code == 200) {
					_self.setData({
						shopName: res.data.obj.shopName
					})

					//_self.showMyToast(_self, res.data.obj.shopCode, 10000)
					mta.Event.stat("smg_renlainshibie", {});
					wx.setStorageSync('shopCode', res.data.obj.shopCode);
					getApp().globalData.common.shopCode = res.data.obj.shopCode;


				} else {
					_self.getShopName();
				}
			}
		})
	},
	payGoods: function(code) {
		var _self = this;
		wx.request({
			url: getApp().globalData.baseUrl + '/applet/pay/payBalance.do',
			data: {
				gbk: code,
				shopCode: getApp().globalData.common.shopCode,
			},
			header: getApp().globalData.header,
			success: function(res) {
				if (res.data.code == 200) {
					wx.showModal({
						title: '提示',
						content: '支付成功' + res.data.obj.amount + '元',
						showCancel: false,
						confirmText: "完成",
						confirmColor: "#ff2f31",
						success: function(res) {
							if (res.confirm) {}
						}
					})

				} else {
					_self.showMyToast(_self, res.data.des)

				}
			},
			fail: function() {
				console.log(1)
			}
		})

	},
	filterNum: function(code) {
		if (code.indexOf("TP") > -1) {
			this.addPayGoods(code);
		} else {
			this.addShopMarket(code, 1);
		}
	},
	payGoodsAction: function(num, code) {
		// mta.Event.stat("smg_btshouyesaoma", {});
		var _self = this;
		wx.showModal({
			title: '提示',
			content: '确认支付' + num + '元',
			showCancel: true,
			success: function(res) {
				if (res.confirm) {
					console.log('付钱')
					_self.payGoods(code);
				}
			}
		})
	},
	popCoupons: function() {
		if (!wx.getStorageSync('fresh')) {
			//新手券
			fetch.newMemVoucher().then(response => {
				wx.setStorageSync('fresh', '1')
				if (response.data.obj && response.data.obj.length > 0) {
					this.setData({
						my_pop: 'my_pop',
						popData: {
							type: 'news',
							imageUrl: getApp().globalData.imageUrl,
							obj: response.data.obj.slice(0, 3)
						}
					})
				}

			})
		} else {
			//日常券
			fetch.getNewCoupon().then(response => {
				if (response.data.obj && response.data.obj.length > 0) {
					this.setData({
						my_pop: 'my_pop',
						popData: {
							type: 'daily',
							imageUrl: getApp().globalData.imageUrl,
							obj: response.data.obj.slice(0, 3)
						}
					})
				}
			})

		}

	},
	closePop: function() {
		util.popClose(this)
	},
	go(e) {
		this.closePop()
		util.popGo(e)
	},
	fitImage: function(type) {
		switch (type) {
			case 1:
				return null;
				break;
			case 2:
				return null;
				break;
			case 3:
				return null;
				break;
			case 4:
				return '../../image/rain.gif';
				break;
			case 5:
				return null;
				break;
			case 0:
				return null;
				break;
			default:
				return null;
		}
	},
	fitUrl: function(url) {
		var res = "?" + url.split('?')[1];
		var qs = (res.length > 0 ? res.substring(1) : ""),
			args = {},
			items = qs.length ? qs.split("&") : [],
			item = null,
			name = null,
			value = null,
			i = 0,
			len = items.length;
		for (i = 0; i < len; i++) {
			item = items[i].split("=");
			name = decodeURIComponent(item[0]);
			value = decodeURIComponent(item[1]);
			if (name.length) {
				args[name] = value;
			}
		}
		return args;
	}


})